package com.cms.controller.admin;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.apache.commons.io.FilenameUtils;

import com.cms.Config;
import com.cms.Feedback;
import com.cms.entity.Resource;
import com.cms.routes.RouteMapping;
import com.cms.util.SystemUtils;
import com.jfinal.kit.PropKit;

@RouteMapping(url = "/admin/resource")
public class ResourceController extends BaseController {
	
	public void saveFolder(){
		String name = getPara("name");
		Resource resource = new Resource();
		resource.setCreateDate(new Date());
		resource.setModifyDate(new Date());
		resource.setIsFolder(true);
		resource.setName(name);
		resource.setValue();
		resource.save();
		renderJson(Feedback.success(resource.getId()));
	}
	
	public void updateFolder(){
		Long id = getParaToLong("id");
		String name = getPara("name");
		Resource resource = new Resource().dao().findById(id);
		resource.setName(name);
		resource.setModifyDate(new Date());
		resource.update();
		renderJson(Feedback.success(new HashMap<>()));
	}
	
	public void saveFile(){
		Long parentId = getParaToLong("parentId");
		String url = getPara("url");
		url = url.replace(SystemUtils.getConfig().getImgUrl(), "");
		Resource resource = new Resource();
		resource.setCreateDate(new Date());
		resource.setModifyDate(new Date());
		resource.setIsFolder(false);
		resource.setName(FilenameUtils.getName(url));
		resource.setUrl(url);
		resource.setParentId(parentId);
		resource.setValue();
		resource.save();
		renderJson(Feedback.success(resource.getId()));
	}
	
	public void deleteFile(){
		Long id = getParaToLong("id");
		new Resource().deleteById(id);
		renderJson(Feedback.success(new HashMap<>()));
	}

	
	public void list() {
		String fromType = getPara("fromType");
		setAttr("fromType", fromType);
		Long parentId = getParaToLong("parentId");
		if(parentId!=null){
			Resource parent = new Resource().dao().findById(parentId);
			setAttr("parent", parent);
			List<Resource> resources = new Resource().dao().findByParentId(parentId);
			setAttr("resources", resources);
		}else{
			List<Resource> resources = new Resource().findRoots();
			setAttr("resources", resources);
		}
		render(getView("resource/list"));
	}
}
